package cn.changeforyou.web.cloud.auth.manager.impl;

import cn.changeforyou.web.cloud.auth.datastruct.OrgTree;
import cn.changeforyou.web.cloud.auth.entity.OrgInfo;
import cn.changeforyou.web.cloud.auth.manager.AuthCacheManager;
import cn.changeforyou.web.cloud.auth.service.OrgInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class AuthCacheManagerImpl implements AuthCacheManager {

    @Resource
    private OrgInfoService orgInfoService;

    @Override
    @Cacheable(value = "orgTree", key = "#root", cacheManager = "simpleCacheManager")
    public OrgTree getOrgTree() {
        //暂时不支持parentId的大小是无序的
        List<OrgInfo> list = orgInfoService.list(new LambdaQueryWrapper<OrgInfo>().orderByAsc(OrgInfo::getParentOrgId));
        OrgTree tree = new OrgTree();
        for (OrgInfo orgInfo : list) {
            Integer parentOrgId = orgInfo.getParentOrgId();
            if(parentOrgId == -1){
                tree.addChildFor(orgInfo, null);
            }else {
                tree.addChildFor(orgInfo, orgInfo.getParentOrgId());
            }
        }
        return tree;
    }
}
